package com.dff.jrfw;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.common.Constant;
import com.dff.jrfw.databinding.ActivitySetPayPsdBinding;
import com.dff.jrfw.model.LoginAccountRecordModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.requestBody.MobileCertDto;
import com.dff.jrfw.requestBody.MobileDeviceDTO;
import com.dff.jrfw.utils.DeviceIdUtil;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.SharedPreferenceUtils;
import com.dff.jrfw.utils.ToastUtil;
import com.dff.jrfw.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

import cn.com.infosec.mobile.android.managers.CertManager;
import cn.com.infosec.mobile.android.managers.UserManager;
import cn.com.infosec.mobile.android.result.Result;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class SetPayPsdActivity extends BaseActivity implements View.OnClickListener {

    private ActivitySetPayPsdBinding binding;
    private int psdVisible = 0;    //默认密码不可见
    private String username;
    private String mobile;
    private String etCode;
    private String typeFrom;


    public static void callMe(Activity context, String username, String mobile, String etCode, String typeFrom) {
        Intent intent = new Intent(context, SetPayPsdActivity.class);
        intent.putExtra("username", username);
        intent.putExtra("mobile", mobile);
        intent.putExtra("etCode", etCode);
        intent.putExtra("typeFrom", typeFrom);
        if (typeFrom.equals("login")) {
            context.startActivityForResult(intent, 666);
        } else {
            context.startActivity(intent);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_set_pay_psd);
        username = getIntent().getStringExtra("username");
        mobile = getIntent().getStringExtra("mobile");
        etCode = getIntent().getStringExtra("etCode");
        typeFrom = getIntent().getStringExtra("typeFrom");
        initView();
    }


    private void initView() {
        binding.ivBack.setOnClickListener(this);
        binding.btnSure.setOnClickListener(this);
        binding.ivEye.setOnClickListener(this);
        binding.ivTip.setOnClickListener(this);
        binding.ivCloseTip.setOnClickListener(this);
        binding.ivInputClearPsd.setOnClickListener(this);
        binding.ivInputClearPsdAgain.setOnClickListener(this);
        binding.etPayPsd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {
                if (isFocus) {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }
            }
        });
        binding.etPayPsdAgain.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean isFocus) {
                if (isFocus) {
                    binding.tvErrorAgain.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }
            }
        });
        binding.etPayPsd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etPayPsd = charSequence.toString().trim();
                if (etPayPsd.length() == 0) {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                    binding.ivInputClearPsd.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearPsd.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.etPayPsdAgain.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String etPayPsdAgain = charSequence.toString().trim();
                if (etPayPsdAgain.length() == 0) {
                    binding.tvErrorAgain.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                    binding.ivInputClearPsdAgain.setVisibility(View.INVISIBLE);
                } else {
                    binding.ivInputClearPsdAgain.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_tip:
                if (binding.ivTipBg.getVisibility() == View.INVISIBLE) {
                    binding.ivTipBg.setVisibility(View.VISIBLE);
                    binding.tvTip.setVisibility(View.VISIBLE);
                    binding.ivCloseTip.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_close_tip:
                binding.ivTipBg.setVisibility(View.INVISIBLE);
                binding.tvTip.setVisibility(View.INVISIBLE);
                binding.ivCloseTip.setVisibility(View.INVISIBLE);
                break;
            case R.id.btn_sure:
                String etPayPsd = binding.etPayPsd.getText().toString().trim();
                String etPayPsdAgain = binding.etPayPsdAgain.getText().toString().trim();

                if (TextUtils.isEmpty(etPayPsd) || etPayPsd.length() < 6) {
                    binding.tvError.setVisibility(View.VISIBLE);
                    binding.viewEtPayPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
                    return;
                } else {
                    binding.tvError.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }

                if (!etPayPsd.equals(etPayPsdAgain)) {
                    binding.tvErrorAgain.setVisibility(View.VISIBLE);
                    binding.viewEtPayPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.red));
                    return;
                } else {
                    binding.tvErrorAgain.setVisibility(View.INVISIBLE);
                    binding.viewEtPayPsdAgainBottomLine.setBackgroundColor(getResources().getColor(R.color.g999999));
                }

                getUserUid(username, etPayPsd);
                Util.hideKeyBoard(binding.btnSure);
                break;
            case R.id.iv_eye:
                if (psdVisible == 0) {
                    psdVisible = 1;
                    binding.ivEye.setImageResource(R.drawable.open_eye);
                    binding.etPayPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    binding.etPayPsdAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    psdVisible = 0;
                    binding.ivEye.setImageResource(R.drawable.cl_eye);
                    binding.etPayPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    binding.etPayPsdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.iv_input_clear_psd:
                binding.etPayPsd.setText("");
                break;
            case R.id.iv_input_clear_psd_again:
                binding.etPayPsdAgain.setText("");
                break;
        }
    }


    private void doSignUp(String userName, String signCode, String pin) {
        UserManager userManager = new UserManager(this);
        userManager.signUp(userName, signCode, new Result.ResultListener() {
            @Override
            public void handleResult(Result result) {
                if (TextUtils.equals(Result.OPERATION_SUCCEED, result.getResultID())) {
                    new CertManager(SetPayPsdActivity.this).requestCert(userName, pin, new Result.ResultListener() {
                        @Override
                        public void handleResult(Result result) {
                            hideLoading();
                            if (result.getResultID().equals(Result.OPERATION_SUCCEED)) {
                                Log.e("TAG", "证书申请成功");
                                SharedPreferenceUtils.getInstance().put(SetPayPsdActivity.this, userName, pin);
                                if (typeFrom.equals("login")) {
                                    ToastUtil.toast("证书下载成功，请重新登录");
                                    setResult(888);
                                    finish();
//                                    saveCertificate(userName, signCode);
                                } else if (typeFrom.equals("forgot")) {
                                    ToastUtil.toast("证书下载成功");
                                    ForgotPsdTwoActivity.callMe(SetPayPsdActivity.this, userName, mobile);
                                } else if (typeFrom.equals("loginTwo")) {
                                    ToastUtil.toast("证书下载成功，请重新登录");
                                    String json = (String) SharedPreferenceUtils.getInstance().get(SetPayPsdActivity.this, Constant.LOGIN_ACCOUNT_RECORD, "");
                                    LoginAccountRecordModel loginAccountRecordModel = GsonUtils.gsonToBean(json, LoginAccountRecordModel.class);
                                    if (loginAccountRecordModel != null && loginAccountRecordModel.getLoginRecord() != null && loginAccountRecordModel.getLoginRecord().size() > 0) {
                                        ArrayList<String> loginRecord = loginAccountRecordModel.getLoginRecord();
                                        LoginTwoActivity.callMe(SetPayPsdActivity.this, loginRecord);
                                    } else {
                                        LoginActivity.callMe(SetPayPsdActivity.this, userName);
                                    }
                                }
                            } else {
                                Toast.makeText(SetPayPsdActivity.this, result.getResultDesc(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    hideLoading();
                    Toast.makeText(SetPayPsdActivity.this, "签约失败:".concat(result.getResultDesc()), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @SuppressLint("SimpleDateFormat")
    private String dateConvert(String date) {
        try {
            Date d = new SimpleDateFormat("yyyy年MM月dd日").parse(date);
            return new SimpleDateFormat("yyyy-MM-dd").format(Objects.requireNonNull(d));
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("xxx", "转换错误");
            return "";
        }
    }

    private void saveCertificate(String userName, String authCode) {
        MobileCertDto mobileCertDto = new MobileCertDto();
        CertManager certManager = new CertManager(this);
        mobileCertDto.setCertCode(userName);
        certManager.getCertField(userName, 1);
        mobileCertDto.setAuthCode(authCode);
        mobileCertDto.setDn(certManager.getCertField(userName, 0));
        mobileCertDto.setSn(certManager.getCertField(userName, 1));
        mobileCertDto.setEffectiveTime(dateConvert(certManager.getCertField(userName, 6)));
        mobileCertDto.setExpireTime(dateConvert(certManager.getCertField(userName, 7)));
        RetrofitUtilsTwo.getService().saveCertificate("1", "1", mobileCertDto).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
                certManager.deleteCert(userName);
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        hideLoading();
                        if (code == 200) {
                            saveDeviceID(userName);
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            certManager.deleteCert(userName);
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        certManager.deleteCert(userName);
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    certManager.deleteCert(userName);
                    hideLoading();
                }
            }
        });
    }

    private void saveDeviceID(String userName){
        CertManager certManager = new CertManager(this);
        MobileDeviceDTO mobileDeviceDTO = new MobileDeviceDTO();
        mobileDeviceDTO.setDeviceId(DeviceIdUtil.getDeviceId(this));
        mobileDeviceDTO.setOsType("Android");
        mobileDeviceDTO.setPhoneManufacturer(android.os.Build.MANUFACTURER);
        RetrofitUtilsTwo.getService().saveDeviceID("1","1",mobileDeviceDTO).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
                certManager.deleteCert(userName);
            }
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        hideLoading();
                        if (code == 200) {
                            ToastUtil.toast("证书下载成功，请重新登录");
                            setResult(888);
                            finish();
                        } else {
                            String msg = jsonObject.getString("msg");
                            certManager.deleteCert(userName);
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        certManager.deleteCert(userName);
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    certManager.deleteCert(userName);
                    hideLoading();
                }
            }
        });
    }


    private void getUserUid(String uno, String etPayPsd) {
        showLoading();
        RetrofitUtilsTwo.getService().getUserUid("1", "1", uno).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            String data = jsonObject.getString("data");
                            if (!"null".equals(data) && !TextUtils.isEmpty(data)) {
                                goDelCert(username, etPayPsd, data);
                            } else {
                                getCerAuthCode(etCode, etPayPsd);
                            }
                        } else if (code == 999) {
                            getCerAuthCode(etCode, etPayPsd);
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


    private void getCerAuthCode(String checkCode, String etCode) {
        RetrofitUtilsTwo.getService().getCerAuthCode("1", "1", mobile, checkCode).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            String signCode = jsonObject.getString("data");
                            doSignUp(username, signCode, etCode);
                        } else if (code == 906) {
                            hideLoading();
                            ToastUtil.toast("验证码错误");
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


    private void goDelCert(String username, String etPayPsd, String uid) {
        RetrofitUtilsTwo.getService().deleteCertByUid("1", "1", uid).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200 || code == 999) {
                            CertManager certManager = new CertManager(SetPayPsdActivity.this);
                            boolean certExist = certManager.isCertExist(username);
                            if (certExist) {
                                boolean deleteCert = certManager.deleteCert(username);
                                if (deleteCert) {
                                    getRefreshCerAuthCode(uid, etPayPsd);
                                } else {
                                    hideLoading();
                                    ToastUtil.toast("本地证书删除失败");
                                }
                            } else {
                                getRefreshCerAuthCode(uid, etPayPsd);
                            }
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


    private void getRefreshCerAuthCode(String uid, String pin) {
        RetrofitUtilsTwo.getService().getRefreshCerAuthCode("1", "1", uid).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            String signCode = jsonObject.getString("data");
                            doSignUp(username, signCode, pin);
                        } else {
                            hideLoading();
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        hideLoading();
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                }
            }
        });
    }


}